package com.experience.util.upload;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.experience.util.frequent.Util;

/**
 * 
 * @ClassName: UploadUtil 
 * @Description: TODO(上传文件工具类) 
 * @author FANGDAJI 
 * @date 2016年11月26日 下午12:53:04 
 * spring-web-4.0.9.RELEASE.jar
 */
public class UploadUtil {

	/**
	 * 
	 * @param request
	 * @param response
	 * @param directory  文件保存目录  如app  不用加/或\\
	 * @return 文件key  files
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static Map<String, String> upload(HttpServletRequest request,String basePath, String directory) throws IllegalStateException, IOException{
		Map<String, String> valsMap = new HashMap<>();
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String key = names.nextElement();
			String value = request.getParameter(key);
			valsMap.put(key, value);
		}
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
		if(multipartResolver.isMultipart(request)){  
			StringBuffer files = new StringBuffer();
			File bashPathFile = new File(basePath, Constant.PREFIX+java.io.File.separator+directory);
			if (!bashPathFile.exists()) {
				bashPathFile.mkdirs();
			}
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
			Iterator<String> iter = multiRequest.getFileNames();  
			while(iter.hasNext()){  
				MultipartFile file = multiRequest.getFile(iter.next());  
				if(file != null){  
					String originalFilename = file.getOriginalFilename();  
					if(originalFilename.trim() !=""){  
						String fileName = Util.UUID() + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());  
						file.transferTo(new File(bashPathFile, fileName));  
						files.append(Constant.PREFIX+"/"+directory+"/"+fileName).append(",");
					}  
				}  
			}
			if (files.length() > 0) {
				valsMap.put("files", files.substring(0, files.length()-1));
			}else{
				valsMap.put("files", "");
			}
		}  
		return valsMap;
	}
}
